package org.monkey.common.gateway.handler;

import static org.monkey.common.constant.entity.ErrorResultEnum.SERVICE_BUSY;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.netty.handler.codec.http.HttpHeaderValues;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.monkey.common.constant.entity.Result;
import org.monkey.common.constant.exception.BaseException;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

/**
 * 自定义限流异常处理
 */
@Slf4j
public class SentinelFallbackHandler implements WebExceptionHandler {

  private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange) {
    log.info("sentinel limited:{}",response.statusCode());
    ServerHttpResponse serverHttpResponse = exchange.getResponse();
    serverHttpResponse.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
    serverHttpResponse.getHeaders().add(HttpHeaders.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON.toString());
    Result<String> result = Result.error(new BaseException(SERVICE_BUSY));
    byte[] returnData = JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8);
    DataBuffer buffer = serverHttpResponse.bufferFactory().wrap(returnData);
    return serverHttpResponse.writeWith(Mono.just(buffer));
  }

  @Override
  public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
    if (exchange.getResponse().isCommitted()) {
      return Mono.error(ex);
    }
    if (!BlockException.isBlockException(ex)) {
      return Mono.error(ex);
    }
    return handleBlockedRequest(exchange, ex)
        .flatMap(response -> writeResponse(response, exchange));
  }

  private Mono<ServerResponse> handleBlockedRequest(
      ServerWebExchange exchange, Throwable throwable) {
    return GatewayCallbackManager.getBlockHandler().handleRequest(exchange, throwable);
  }
}
